package com.why.zing.delaycore.service.impl;

import com.why.zing.delaycore.constant.RedisQueueKey;
import com.why.zing.delaycore.service.ConsumerService;
import com.why.zing.delaycore.util.RestTemplateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

import static org.springframework.http.HttpHeaders.CONTENT_TYPE;

/**
 * 消费者类，对ReadyQueue中的消息进行消费
 *
 * @author 睁眼看世界
 * @date 2020年1月16日
 */
@Slf4j
@Service
public class ConsumerServiceImpl implements ConsumerService {

    @Autowired
    private RestTemplateUtils httpClient;


    /**
     * 消费ReadyQueue的消息
     *
     * @param url  请求URL
     * @param body 消息内容
     * @return 执行结果
     */
    @Override
    public Boolean consumerMessage(String url, String body) {
        log.info("consumerMessage url is [{}], param is [{}]", url, body);
        try {
            Map<String, String> headers = new HashMap<>();
            headers.put(CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE);
            ResponseEntity<String> responseEntity = httpClient.post(url, headers, body, String.class);
            log.info("consumerMessage result is [{}]", responseEntity.getBody());
            HttpStatus statusCode = responseEntity.getStatusCode();
            String response = responseEntity.getBody();
            return statusCode.is2xxSuccessful() && StringUtils.equals(response, RedisQueueKey.SUCCESS);
        } catch (Exception e) {
            log.error("consumerMessage error", e);
        }
        return Boolean.FALSE;
    }

}
